/* Copyright 2009 Requirements Management System 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.mags.remas.view;

import java.util.Date;
import java.util.HashSet; 
import java.util.List;   
import java.util.Set;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.validator.GenericValidator;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.PlatformUI;
import org.mags.common.EngineContext;
import org.mags.remas.control.PagedCommentsController;
import org.mags.remas.model.entity.Entity;
import org.mags.remas.model.entity.EntityCategory;
import org.mags.remas.model.entity.EntityComment;
import org.mags.remas.model.entity.EntityRelationship;
import org.mags.remas.view.commons.IActionMenuMaker;
import org.mags.remas.view.commons.ImageProvider;
import org.mags.remas.view.commons.TreeActionMaker;
import org.mags.remas.view.dialogs.FindCommentsDialog;
import org.mags.remas.view.widgets.RelationshipTreeViewer;

/**
 * 
 * @author Mario Gaitan
 *
 */
public class PagedCommentsView extends AbstractEntityView 
	implements IActionMenuMaker {
	
	public final static String ID="org.mags.remas.view.pagedCommentsEditor";
	private PagedCommentsController viewController;
	private TreeActionMaker treeActionMaker;
	private FindCommentsDialog findDialog = new FindCommentsDialog(PlatformUI.getWorkbench().getDisplay());
	private Action findAction;
	private Action prevPageAction;
	private Action nextPageAction;
	private Action lastPageAction;
	private Action firstPageAction;
	private Action selectInViewAction;
	private Entity root;
	
	@Override
	public void dispose() {
		super.dispose();
		findDialog.dispose();
	}
	private void makePageActions(IActionBars bars) {
		firstPageAction = new Action() {
			public void run() {
				viewController.moveFirstPage();
				getTreeViewer().refresh();
			}
		};
		firstPageAction.setText("first");
		firstPageAction.setToolTipText("first page");
		firstPageAction.setImageDescriptor(ImageProvider.getCommonImageDescriptor("first.png"));
		bars.getToolBarManager().add(firstPageAction);		
		prevPageAction = new Action() {
			public void run() {
				viewController.movePrevPage();
				getTreeViewer().refresh();
			}
		};
		prevPageAction.setText("previous");
		prevPageAction.setToolTipText("previous page");
		prevPageAction.setImageDescriptor(ImageProvider.getCommonImageDescriptor("prev.png"));
		bars.getToolBarManager().add(prevPageAction);
		nextPageAction = new Action() {
			public void run() {
				viewController.moveNextPage();
				getTreeViewer().refresh();
			}
		};
		nextPageAction.setText("next");
		nextPageAction.setToolTipText("next page");
		nextPageAction.setImageDescriptor(ImageProvider.getCommonImageDescriptor("next.png"));
		bars.getToolBarManager().add(nextPageAction);
		lastPageAction = new Action() {
			public void run() {
				viewController.moveLastPage();
				getTreeViewer().refresh();
			}
		};
		lastPageAction.setText("last");
		lastPageAction.setToolTipText("last page");
		lastPageAction.setImageDescriptor(ImageProvider.getCommonImageDescriptor("last.png"));
		bars.getToolBarManager().add(lastPageAction);				
	}
	public PagedCommentsView() {
		super(EngineContext.getDataContext().getEntityProviderFactory().getViewTypeProvider().getLISTVIEW());
		viewController = new PagedCommentsController();
	}
	@Override
	public void createPartControl(Composite parent) {
		RelationshipTreeViewer treeViewer = new RelationshipTreeViewer(parent, SWT.NONE, viewType, false, false);
		setTreeViewer(treeViewer);
		treeViewer.addRelationshipTreeViewerListener(this);
		treeViewer.setColumnProperties(new String[]{"name"});
		getSite().setSelectionProvider(treeViewer);		
		treeViewer.setContentProvider(viewController);
		treeViewer.setLabelProvider(viewController);
		root = new Entity();
		root.setCode("FIND");
		root.setEntityId(-1);
		root.setCreationDate(new Date());
		root.setChangeDate(new Date());
		root.setCreatedBy("");
		root.setUpdatedBy("");
		final EntityRelationship rootRelationship = new EntityRelationship();
		rootRelationship.setEntity(root);
		rootRelationship.setEntityType(root.getEntityType());
		rootRelationship.setHierarchicalPath("/");		
		rootRelationship.setParent(new EntityRelationship());
		rootRelationship.getParent().setHierarchicalPath("");
		treeViewer.setRoot(rootRelationship);		
		treeActionMaker = new TreeActionMaker(super.getTreeViewer(), viewController, super.getSite());
		treeActionMaker.makeActions();
		treeActionMaker.makeMenu();
		treeActionMaker.setActionMenuMaker(this);	
		IActionBars bars = getViewSite().getActionBars();
		
		findAction = new Action() {
			public void run() {
				try {		
					findDialog.show();
					EntityRelationship _filter = null;
					if(findDialog.getFilter()!=null) {
						_filter = new EntityRelationship();
						_filter.setEntity(new Entity());
						Set<EntityComment> entityComments = new HashSet<EntityComment>();
						_filter.getEntity().setEntityComments(entityComments);
						_filter.getEntity().getEntityComments().add(findDialog.getFilter());
					}
					viewController.setFilter(_filter);
					getTreeViewer().remove(rootRelationship);
					getTreeViewer().setRoot(rootRelationship);
				} catch(Exception e) {
					exceptionCatched(e);
				}
			}
		};
		findAction.setText("find");
		findAction.setToolTipText("find elements");
		findAction.setImageDescriptor(ImageProvider.getCommonImageDescriptor("find.png"));
		
		bars.getMenuManager().add(findAction);
		bars.getMenuManager().add(treeActionMaker.getEditAction());
		bars.getMenuManager().add(treeActionMaker.getRefreshAction());
		selectInViewAction= new Action() {
			public void run() {
				EntityRelationship relationship = getTreeViewer().getSelectedElement();
				if(relationship.getEntity().getEntityId()>0) {
					EntityCategory entityCategory = relationship.getEntity().getEntityType().getEntityCategory();
					EntityView entityView = (EntityView)getViewSite().getPage().findView(entityCategory.getIdView());
					if(entityView==null) {
						try {
							entityView = (EntityView)getViewSite().getPage().showView(entityCategory.getIdView());
						} catch (Exception e) {
							throw new RuntimeException(e);
						}
					}		
					entityView.getTreeViewer().findAndSelectRelationship(relationship);
					getViewSite().getPage().bringToTop(entityView);
				}
			}
		};
		selectInViewAction.setText("select in view");
		selectInViewAction.setToolTipText("select in view");
		selectInViewAction.setImageDescriptor(ImageProvider.getCommonImageDescriptor("select.png"));		
		bars.getMenuManager().add(selectInViewAction);
		
		makePageActions(bars);
		bars.getToolBarManager().add(findAction);
	}
	public void makeMenuForDrop(IMenuManager manager) {
	}
	public void makeMenuForRightClick(IMenuManager manager) {
		final EntityRelationship entityRelationship = super.getTreeViewer().getSelectedElement();
		Entity entity = entityRelationship.getEntity();
		if(entity.getEntityId()>-1) {
			manager.add(findAction);
			manager.add(new Separator());
			manager.add(treeActionMaker.getEditAction());
			manager.add(treeActionMaker.getRefreshAction());
			manager.add(selectInViewAction);
			manager.add(new Separator());
			if(root.getEntityId()!=entity.getEntityId()) {
				manager.add(treeActionMaker.getCommentsAction());
				manager.add(treeActionMaker.getAddCommentAction());
			}		
			manager.add(treeActionMaker.getPropertiesAction());
		} else {
			manager.add(findAction);
			manager.add(treeActionMaker.getRefreshAction());
			manager.add(new Separator());
			manager.add(treeActionMaker.getPropertiesAction());
		}
	}
	public boolean dragAndDrop(EntityRelationship target, List<EntityRelationship> elementsDroped) {
		treeActionMaker.getMenuDrop().setVisible(true);
		return true;
	}
	public void doubleClick(EntityRelationship first) {
		String defaultAction = first.getEntity().getEntityType().getDefaultAction();
		if(GenericValidator.isBlankOrNull(defaultAction)) 
			defaultAction = "edit";
		defaultAction = defaultAction+"Action";
		try {
			Object action = PropertyUtils.getProperty(treeActionMaker, defaultAction);
			if(action!=null&&action instanceof Action)
				((Action)action).run();
		} catch (Exception e) {
			exceptionCatched(e);
		}		
	}
	@Override
	public void keyPressed(EntityRelationship first, KeyEvent keyEvent) {
	}
	@Override
	public void update(EntityRelationship entityRelationship, String property, Object value) {
	}		
}
